import cv2
import numpy as np


def decode(bin_file: str):
    with open(bin_file, 'wb') as fileSave:
        for k in range(24):
            image = cv2.imread('res/res'+ str(k) + '.png')
            rows, cols, channels = image.shape
            s=''
            # 图像解码成二进制文件
            for row in range(rows):
                for col in range(cols):
                    a = image[row, col]
                    if a[0] > 127 and a[1] > 127 and a[2] > 127:
                        s = s + '1'
                    else:
                        s = s + '0'
                    if len(s) == 8:
                        res = 0
                        for i, c in enumerate(s):
                            if c == '1':
                                res += pow(2, i)
                        fileSave.write(np.uint8(res))
                        s = ''


def video2img(video_file: str):
    cap = cv2.VideoCapture(video_file)
    ret = True
    n = 0
    while ret:
        ret, frame = cap.read()
        if ret:
            cv2.imwrite('res/res' + str(n) + '.png', frame)
            n += 1


if __name__ == '__main__':
    # decode
    phone_video_file = input('请输入手机拍摄的视频文件名:')  # video.avi
    decode_bin_file = input('请输入解码后的二进制文件名:')  # result.bin
    video2img(phone_video_file)
    print('Finish convert to image.')
    decode(decode_bin_file)
    print('Finish decoding the result.')
